﻿#if UNITY_EDITOR

namespace Blaze.FileSystems
{
    using System.IO;
    using System.Security.Cryptography;

    public class IndexBuilder
    {
        public IndexBuilder(Stream output)
        {
            mPkgBuilder = new PkgBuilder(output);
        }

        public IndexBuilder Add(string path, string fullPath, IndexEntryType type = IndexEntryType.Plain)
        {
            using (var stream = File.Open(fullPath, FileMode.Open))
            {
                return Add(path, stream, type);
            }
        }

        public IndexBuilder Add(string path, Stream stream, IndexEntryType type = IndexEntryType.Plain)
        {
            var contentStream = new MemoryStream();
            var writer = new BinaryWriter(contentStream);
            var entryTableItem = new IndexFile.EntryTableItem
            {
                Hash = mSha1.ComputeHash(stream),
                Type = (byte) type,
            };
            entryTableItem.Write(writer);
            writer.Flush();
            contentStream.Position = 0;
            mPkgBuilder.Add(path, contentStream);
            return this;
        }

        public IndexBuilder Finish()
        {
            mPkgBuilder.Finish();
            return this;
        }

        private readonly SHA1 mSha1 = new SHA1Cng();
        private readonly PkgBuilder mPkgBuilder;
    }
}

#endif